
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { BookOpen, CheckCircle, ExternalLink } from "lucide-react";

interface Question {
  id: string;
  question: string;
  options: {
    value: string;
    label: string;
    philosophy: 'constructivist' | 'behaviorist' | 'inquiry' | 'systematic';
  }[];
}

const questions: Question[] = [
  {
    id: "1",
    question: "What best describes your role in the classroom?",
    options: [
      { value: "A", label: "Facilitator of discovery", philosophy: "constructivist" },
      { value: "B", label: "Knowledge transmitter", philosophy: "behaviorist" },
      { value: "C", label: "Question-driven coach", philosophy: "inquiry" },
      { value: "D", label: "Systems planner", philosophy: "systematic" }
    ]
  },
  {
    id: "2", 
    question: "How do you prefer students to demonstrate learning?",
    options: [
      { value: "A", label: "Group projects & real-world application", philosophy: "constructivist" },
      { value: "B", label: "Tests and structured answers", philosophy: "behaviorist" },
      { value: "C", label: "Portfolios and open-ended tasks", philosophy: "inquiry" },
      { value: "D", label: "Performance against rubrics", philosophy: "systematic" }
    ]
  },
  {
    id: "3",
    question: "When students struggle, you typically:",
    options: [
      { value: "A", label: "Guide them to find their own solutions", philosophy: "constructivist" },
      { value: "B", label: "Break down the concept into smaller steps", philosophy: "behaviorist" },
      { value: "C", label: "Ask probing questions to stimulate thinking", philosophy: "inquiry" },
      { value: "D", label: "Provide structured support materials", philosophy: "systematic" }
    ]
  },
  {
    id: "4",
    question: "Your ideal classroom environment is:",
    options: [
      { value: "A", label: "Collaborative and student-centered", philosophy: "constructivist" },
      { value: "B", label: "Structured with clear expectations", philosophy: "behaviorist" },
      { value: "C", label: "Question-rich and exploratory", philosophy: "inquiry" },
      { value: "D", label: "Organized with systematic routines", philosophy: "systematic" }
    ]
  },
  {
    id: "5",
    question: "You believe learning happens best when:",
    options: [
      { value: "A", label: "Students build knowledge through experience", philosophy: "constructivist" },
      { value: "B", label: "Information is presented clearly and practiced", philosophy: "behaviorist" },
      { value: "C", label: "Students investigate authentic problems", philosophy: "inquiry" },
      { value: "D", label: "Learning follows a logical sequence", philosophy: "systematic" }
    ]
  }
];

const philosophyResults = {
  constructivist: {
    title: "Constructivist Educator",
    description: "You facilitate discovery-based learning and encourage student exploration",
    strategies: [
      "Use project-based learning approaches",
      "Encourage peer collaboration and discussion",
      "Connect learning to real-world experiences"
    ],
    resources: [
      "Collaborative Learning Templates",
      "Project-Based Learning Community",
      "Inquiry-Based Lesson Plans"
    ]
  },
  behaviorist: {
    title: "Instructional Architect", 
    description: "You excel at structured teaching and clear learning progressions",
    strategies: [
      "Design clear learning objectives and outcomes",
      "Use systematic skill-building sequences",
      "Implement effective feedback systems"
    ],
    resources: [
      "Structured Lesson Templates",
      "Assessment Design Tools",
      "Curriculum Planning Community"
    ]
  },
  inquiry: {
    title: "Question-Driven Coach",
    description: "You inspire learning through questioning and critical thinking",
    strategies: [
      "Develop powerful questioning techniques",
      "Create problem-solving scenarios",
      "Foster student-led investigations"
    ],
    resources: [
      "Socratic Method Templates",
      "Critical Thinking Community",
      "Inquiry Learning Resources"
    ]
  },
  systematic: {
    title: "Systematic Planner",
    description: "You create organized, efficient learning environments",
    strategies: [
      "Develop comprehensive curriculum maps",
      "Use data-driven instruction methods", 
      "Implement systematic assessment strategies"
    ],
    resources: [
      "Curriculum Planning Tools",
      "Data Analysis Templates",
      "Systematic Teaching Community"
    ]
  }
};

interface TeachingPhilosophyAssessmentProps {
  onComplete: (result: string, description: string) => void;
  currentResult?: {
    status: string;
    result?: string;
    description?: string;
  };
}

export function TeachingPhilosophyAssessment({ onComplete, currentResult }: TeachingPhilosophyAssessmentProps) {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<Record<string, string>>({});
  const [showResults, setShowResults] = useState(false);
  const [result, setResult] = useState<keyof typeof philosophyResults | null>(null);

  const handleAnswer = (questionId: string, value: string) => {
    setAnswers(prev => ({ ...prev, [questionId]: value }));
  };

  const handleNext = () => {
    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(prev => prev + 1);
    } else {
      calculateResult();
    }
  };

  const handlePrevious = () => {
    if (currentQuestion > 0) {
      setCurrentQuestion(prev => prev - 1);
    }
  };

  const calculateResult = () => {
    const philosophyCounts = {
      constructivist: 0,
      behaviorist: 0,
      inquiry: 0,
      systematic: 0
    };

    Object.entries(answers).forEach(([questionId, answerValue]) => {
      const question = questions.find(q => q.id === questionId);
      const selectedOption = question?.options.find(opt => opt.value === answerValue);
      if (selectedOption) {
        philosophyCounts[selectedOption.philosophy]++;
      }
    });

    const dominantPhilosophy = Object.entries(philosophyCounts).reduce((a, b) => 
      philosophyCounts[a[0] as keyof typeof philosophyCounts] > philosophyCounts[b[0] as keyof typeof philosophyCounts] ? a : b
    )[0] as keyof typeof philosophyResults;

    setResult(dominantPhilosophy);
    setShowResults(true);
  };

  const handleComplete = () => {
    if (result) {
      const resultData = philosophyResults[result];
      onComplete(resultData.title, resultData.description);
    }
  };

  const progress = ((currentQuestion + 1) / questions.length) * 100;
  const answeredQuestions = Object.keys(answers).length;

  if (showResults && result) {
    const resultData = philosophyResults[result];
    
    return (
      <div className="space-y-6">
        <Card className="bg-gradient-to-r from-blue-50 to-indigo-50 border-blue-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-green-600" />
              Your Teaching Philosophy: {resultData.title}
            </CardTitle>
            <CardDescription>{resultData.description}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid md:grid-cols-2 gap-6">
              <div>
                <h4 className="font-medium mb-3">Personalized Teaching Strategies</h4>
                <ul className="space-y-2">
                  {resultData.strategies.map((strategy, index) => (
                    <li key={index} className="flex items-start gap-2 text-sm">
                      <div className="w-1.5 h-1.5 rounded-full bg-blue-600 mt-2 flex-shrink-0" />
                      {strategy}
                    </li>
                  ))}
                </ul>
              </div>
              
              <div>
                <h4 className="font-medium mb-3">Recommended Resources</h4>
                <div className="space-y-2">
                  {resultData.resources.map((resource, index) => (
                    <Button 
                      key={index} 
                      variant="outline" 
                      size="sm" 
                      className="w-full justify-start text-sm h-auto py-2"
                    >
                      <ExternalLink className="w-3 h-3 mr-2" />
                      {resource}
                    </Button>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <div className="flex justify-center">
          <Button onClick={handleComplete} className="px-8">
            Save Results
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Progress */}
      <div className="space-y-2">
        <div className="flex justify-between text-sm">
          <span>Question {currentQuestion + 1} of {questions.length}</span>
          <span>{answeredQuestions} answered</span>
        </div>
        <Progress value={progress} className="h-2" />
      </div>

      {/* Question */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">
            {questions[currentQuestion].question}
          </CardTitle>
        </CardHeader>
        <CardContent>
          <RadioGroup
            value={answers[questions[currentQuestion].id] || ""}
            onValueChange={(value) => handleAnswer(questions[currentQuestion].id, value)}
          >
            {questions[currentQuestion].options.map((option) => (
              <div key={option.value} className="flex items-center space-x-2 p-3 rounded-lg hover:bg-accent/50 transition-colors">
                <RadioGroupItem value={option.value} id={option.value} />
                <Label htmlFor={option.value} className="flex-1 cursor-pointer">
                  <span className="font-medium mr-2">{option.value}.</span>
                  {option.label}
                </Label>
              </div>
            ))}
          </RadioGroup>
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button 
          variant="outline" 
          onClick={handlePrevious}
          disabled={currentQuestion === 0}
        >
          Previous
        </Button>
        
        <Button 
          onClick={handleNext}
          disabled={!answers[questions[currentQuestion].id]}
        >
          {currentQuestion === questions.length - 1 ? 'View Results' : 'Next'}
        </Button>
      </div>
    </div>
  );
}
